package cn.chiship.sdk.third.ali;

import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import cn.chiship.sdk.core.properties.CommonConfigProperties;
import cn.chiship.sdk.core.util.PrintUtil;
import cn.chiship.sdk.third.core.common.ThirdConstants;
import cn.chiship.sdk.third.core.model.BaseConfigModel;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;

/**
 * 阿里云短信工具
 *
 * @author lijian
 * <p>
 * AliDySmsUtil aliDySmsUtil = AliDySmsUtil.getInstance() .config() .load("智舰工作室",
 * "SMS_147418172"); Map<String, String> paramsMap = new HashMap<>(2);
 * paramsMap.put("code", "123421"); aliDySmsUtil.sendSms("18363003321", paramsMap)
 */
public class AliDySmsUtil {

    CommonConfigProperties commonConfigProperties = CommonConfigProperties.getInstance();

    private static final Logger LOGGER = LoggerFactory.getLogger(AliDySmsUtil.class);
    static final String PRODUCT = "Dysmsapi";
    static final String DOMAIN = "dysmsapi.aliyuncs.com";

    static final String REGION_HANGZHOU = "cn-hangzhou";

    static final String TIME_OUT = "10000";


    private String aliDySmsSignName;

    private String aliDySmsTemplateCode;

    private BaseConfigModel baseConfigModel;

    private static AliDySmsUtil instance;

    private AliDySmsUtil() {
    }

    public static synchronized AliDySmsUtil getInstance() {
        if (instance == null) {
            instance = new AliDySmsUtil();
        }
        return instance;
    }

    public AliDySmsUtil config() {
        try {
            this.baseConfigModel = new BaseConfigModel(commonConfigProperties.getValue("third.sms.ali.accessKey"),
                    commonConfigProperties.getValue("third.sms.ali.accessSecret"));
        } catch (MissingResourceException e) {
            throw new SystemErrorException(ThirdConstants.ERROR_EXIST_TIP_1);
        }
        return this;
    }

    public AliDySmsUtil config(BaseConfigModel baseConfigModel) {
        this.baseConfigModel = baseConfigModel;
        return this;
    }

    public AliDySmsUtil load(String signName, String templateCode) {
        this.aliDySmsSignName = signName;
        this.aliDySmsTemplateCode = templateCode;
        return this;
    }

    public BaseResult sendSms(String mobile, Map<String, String> paramsMap) {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", TIME_OUT);
            System.setProperty("sun.net.client.defaultReadTimeout", TIME_OUT);

            IClientProfile profile = DefaultProfile.getProfile(REGION_HANGZHOU, this.baseConfigModel.getAppKey(),
                    this.baseConfigModel.getAppSecret());
            DefaultProfile.addEndpoint(REGION_HANGZHOU, REGION_HANGZHOU, PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            request.setSignName(this.aliDySmsSignName);
            request.setTemplateCode(this.aliDySmsTemplateCode);
            if (null != paramsMap) {
                request.setTemplateParam(JSON.toJSONString(paramsMap));
            }
            SendSmsResponse response = acsClient.getAcsResponse(request);
            LOGGER.info("短信接口返回的数据----------------");
            LOGGER.info("Code={}", response.getCode());
            LOGGER.info("Message={}", response.getMessage());
            LOGGER.info("RequestId={}", response.getRequestId());
            LOGGER.info("BizId={}", response.getBizId());
            if (response.getCode() != null && ThirdConstants.STRING_OK.equals(response.getCode())) {
                BaseResult baseResult = querySendDetails(mobile, response.getBizId());
                if (!baseResult.isSuccess()) {
                    return baseResult;
                }
                return BaseResult.ok();
            } else {
                return BaseResult.error(response.getMessage());
            }
        } catch (ClientException e) {
            return BaseResult.error(e.getErrMsg());
        }

    }

    public BaseResult querySendDetails(String mobile, String bizId) {

        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", TIME_OUT);
            System.setProperty("sun.net.client.defaultReadTimeout", TIME_OUT);

            IClientProfile profile = DefaultProfile.getProfile(REGION_HANGZHOU, this.baseConfigModel.getAppKey(),
                    this.baseConfigModel.getAppSecret());
            DefaultProfile.addEndpoint(REGION_HANGZHOU, REGION_HANGZHOU, PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            QuerySendDetailsRequest request = new QuerySendDetailsRequest();
            request.setPhoneNumber(mobile);
            request.setBizId(bizId);
            SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
            request.setSendDate(ft.format(new Date()));
            request.setPageSize(10L);
            request.setCurrentPage(1L);
            QuerySendDetailsResponse response = acsClient.getAcsResponse(request);
            if (response.getCode() != null && ThirdConstants.STRING_OK.equals(response.getCode())) {
                return BaseResult.ok(response.getSmsSendDetailDTOs());
            } else {
                return BaseResult.error(response.getMessage());
            }
        } catch (ClientException e) {
            return BaseResult.error(e.getErrMsg());
        }
    }

    public static void main(String[] args) {
        AliDySmsUtil aliDySmsUtil = AliDySmsUtil.getInstance().config().load("智舰工作室", "SMS_253070547");
        Map<String, String> paramsMap = new HashMap<>(2);
        paramsMap.put("code", "123421");
        PrintUtil.console(aliDySmsUtil.sendSms("18363003321", paramsMap));
        PrintUtil.console(aliDySmsUtil.querySendDetails("15153159223", "8729232351099125018^0"));
        PrintUtil.console(aliDySmsUtil.querySendDetails("18363003321", "117912235098231817"));
    }

}
